package testJdk.nio.testChannel;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class TestSocketChannel {
    public static void main(String[] args) throws Exception {

        // 建立socketChannel，并连接服务端
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("localhost", 8888));

        // 设置为非阻塞连接
        socketChannel.configureBlocking(false);

        // 定义buffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        // 读取服务端返回的数据
        int read = socketChannel.read(byteBuffer);
        while (read != -1) {
            System.out.println("读取了:" + read);
            // 反转buffer的读写模式
            byteBuffer.flip();
            while (byteBuffer.hasRemaining()) {
                System.out.print((char) byteBuffer.get());
            }
            byteBuffer.clear();
            // 再次读取，并改变read的值，如果此时channel中没有数据了，就返回-1
            read = socketChannel.read(byteBuffer);
        }
        socketChannel.close();
        System.out.println("read over");
    }
}
